package com.qianniu.napi.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.Qgettype;
import com.qianniu.napi.admin.entity.penum.Utype;
import com.qianniu.napi.admin.mapper.CouponMapper;
import com.qianniu.napi.admin.mapper.CoupontplMemberMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-07
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Autowired
    CouponMapper couponMapper;
    @Autowired
    ICouponService couponService;
    @Autowired
    ICouponTplService couponTplService;
    @Autowired
    ILeagueMemberService leagueMemberService;
    @Autowired
    private ICouponTplShareService couponTplShareService;
    @Autowired
    IRedisService redisService;
    @Autowired
    CoupontplMemberMapper coupontplMemberMapper;

    //用户通过订单礼包购买的券
    public List<Coupon> getStoreCoupon(Long uid, Long oid) {
        return couponMapper.selectStoreCoupon(uid, oid);
    }

    public Long lingQuan(String sn, Long zfuid, Long uid, CouponTpl ctpl, Qgettype oritype) {

        Coupon coupon = new Coupon();
        coupon.setIsUnused(1);//未使用
        coupon.setIsUsed(0);//已使用
        coupon.setIsForever(ctpl.getIsForever());//永久有效
        coupon.setIsOutdate(0);//已过期
        coupon.setState(1);

        coupon.setMid(ctpl.getMid());
        coupon.setMpid(ctpl.getMpid());
        coupon.setUid(uid);    //领券用户
        coupon.setZfuid(zfuid);//转发用户
        if (zfuid != null) coupon.setZfname(redisService.getUser(zfuid).getNickName());
        else if (ctpl.getSid() != null && ctpl.getSid().longValue() > 0) coupon.setZfname("店主");
        coupon.setSid(ctpl.getSid());
        coupon.setCreatetime(new Date());

        coupon.setTplid(ctpl.getId());
        coupon.setType(ctpl.getType());
        coupon.setName(ctpl.getName());
        coupon.setSlogo(ctpl.getSlogo());
        coupon.setSname(ctpl.getSname());
        coupon.setRemark(ctpl.getRemark());

        coupon.setCno(StringUtil.getQuanCode(ctpl.getMid()));
        coupon.setSn(sn);

        coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
        coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
        coupon.setCost(ctpl.getCost());
        coupon.setUsemin(ctpl.getUsemin());
        coupon.setOriginType(oritype.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

        coupon.insert();

        CouponTpl ctpl2 = new CouponTpl();
        ctpl2.setUse(ctpl.getUse() + 1);
        ctpl2.setId(ctpl.getId());
        ctpl2.setModifytime(new Date());
        ctpl2.updateById();

        return coupon.getId();
    }

    public Long lingQuantongji(String sn, Long zfuid, Long uid, CouponTpl ctpl, Qgettype oritype, boolean ishuiyuan) {

        //===============领取券
        Coupon coupon = new Coupon();
        coupon.setIsUnused(1);//未使用
        coupon.setIsUsed(0);//已使用
        coupon.setIsForever(ctpl.getIsForever());//永久有效
        coupon.setIsOutdate(0);//已过期
        coupon.setState(1);

        coupon.setMid(ctpl.getMid());
        coupon.setMpid(ctpl.getMpid());
        coupon.setUid(uid);    //领券用户
        coupon.setZfuid(zfuid);//转发用户
        if (zfuid != null) coupon.setZfname(redisService.getUser(zfuid).getNickName());
        else if (ctpl.getSid() != null && ctpl.getSid().longValue() > 0) coupon.setZfname("店主");
        coupon.setSid(ctpl.getSid());
        coupon.setCreatetime(new Date());

        coupon.setTplid(ctpl.getId());
        coupon.setType(ctpl.getType());
        coupon.setName(ctpl.getName());
        coupon.setSlogo(ctpl.getSlogo());
        coupon.setSname(ctpl.getSname());
        coupon.setRemark(ctpl.getRemark());

        coupon.setCno(StringUtil.getQuanCode(ctpl.getMid()));
        coupon.setSn(sn);

        coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
        coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
        coupon.setCost(ctpl.getCost());
        coupon.setUsemin(ctpl.getUsemin());
        coupon.setOriginType(oritype.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

        coupon.insert();

        //===============更新券模板
        CouponTpl ctpl2 = new CouponTpl();
        ctpl2.setUse(ctpl.getUse() + 1);
        ctpl2.setId(ctpl.getId());
        ctpl2.setModifytime(new Date());
        ctpl2.updateById();

        //===============更新CouponTplShare券分享统计
        if (ctpl.getSid() != null) {
            CouponTplShare couponshare = new CouponTplShare();

            couponshare.setTplid(ctpl.getId());
            couponshare.setQuanid(coupon.getId());
            couponshare.setFenxiao(ctpl.getFenxiao());
            couponshare.setZfuid(zfuid);
            couponshare.setGetuid(uid);

            couponshare.setSid(ctpl.getSid());
            couponshare.setLeagueid(ctpl.getLeagueid());
            couponshare.setCreateday(DateUtil.getToday());
            couponshare.setCreatetime(new Date());
            couponshare.setXinke(ishuiyuan ? 1 : 0);
            couponshare.setIshuiyuan(ishuiyuan ? 1 : 0);

            couponshare.insert();
        }

        return coupon.getId();
    }

    public Boolean conponConfirm(String sn, Long couponId, Long uid) {

        Coupon coupon = couponService.selectById(couponId);
        if (coupon == null) return false;

        coupon.setSn(sn);
        coupon.setIsUsed(1);
        coupon.setIsUnused(0);
        coupon.setState(-1);
        coupon.setUsetime(new Date());
        coupon.setModifier(uid);
        coupon.setModifytime(new Date());
        boolean flag = coupon.updateById();

        //更新券模板
        CouponTpl couponTpl = couponTplService.selectById(coupon.getTplid());
        if (couponTpl != null) {
            couponTpl.setUsed(couponTpl.getUsed() == null ? 1 : couponTpl.getUsed() + 1);//已使用
            couponTpl.setModifytime(new Date());
            couponTpl.updateById();
            //券分销,是在用户领券动作触发
        }

        //更新券模板统计数据
        CouponTplShare couponshare = couponTplShareService.selectOne(new EntityWrapper<CouponTplShare>()
                .setSqlSelect("isused,id,tplid,quanid")
                .eq("tplid", coupon.getTplid()).eq("iszhuanfa", 0).eq("quanid", coupon.getId()));
        if (couponshare != null) {
            couponshare.setIsused(1);
            couponshare.updateById();
        }
        CouponTplShare updateshare = new CouponTplShare();
        updateshare.setUtype(Utype.kehu.getVal());

        couponTplShareService.update(updateshare, new EntityWrapper<CouponTplShare>().eq("getuid", uid));

        if (coupon.getSid() == null) return true;
        Long sid = coupon.getSid();

        //更新最新消费日期
        LeagueMember leagueMember = leagueMemberService.selectOne(new EntityWrapper<LeagueMember>()
                .setSqlSelect("id,lastxf,uid,shareid").eq("uid", uid).eq("sid", sid));
        if (leagueMember != null) {
            leagueMember.setLastxf(DateUtil.getToday());
            leagueMember.updateById();
        }

//        Long shareid = leagueMember.getShareid();
        Long shareid = coupon.getZfuid();
        if (shareid != null) {
            //更新顾客变铁杆粉丝
            LeagueMember smember = leagueMemberService.selectOne(new EntityWrapper<LeagueMember>()
                    .setSqlSelect("id,lastxf,uid,shareid,utype,mlevel").eq("uid", shareid).eq("sid", sid));
            boolean update = false;
            boolean shengji = false;
            if (smember != null && smember.getUtype() != null && smember.getUtype().intValue() > 0) {
                update = true;
                smember.setUtype(Utype.tiegan.getVal());
            }

            List<CoupontplMember> cmembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
                    .setSqlSelect("max(mlevel) mlevel")
                    .eq("sid", coupon.getSid()));
            int maxlevel = cmembers.size() == 0 || cmembers.get(0) == null || cmembers.get(0).getMlevel() == null ? -1 : cmembers.get(0).getMlevel();

//            int sharecout = leagueMemberService.selectCount(new EntityWrapper<LeagueMember>()
//                    .eq("sid", sid).ge("utype", 1).eq("shareid", shareid));

            int sharecout = couponTplShareService.selectCount(new EntityWrapper<CouponTplShare>()
                    .setSqlSelect("distinct getuid")
                    .eq("sid", sid).ge("utype", 1).eq("zfuid", shareid));

            //领取联盟会员之后默认是试用会员等级0，推荐联盟会员不升级，推荐商家会员升级
            //从店主那里获取商家会员默认1级，推荐3人升2级，推荐6人升级3，推荐9人升4级。。。
            int tolevel = sharecout / 3 + 1;
            //每推荐三个人成为会员升一级
            tolevel = tolevel <= maxlevel ? tolevel : maxlevel;

            if (smember != null && smember.getMlevel().intValue() < tolevel && maxlevel >= 1 && smember.getMlevel() >= 1) {
                update = true;
                shengji = true;
                smember.setYaoqing(sharecout);
                smember.setMlevel(tolevel);
            }

            if (update) {
                smember.setModifytime(new Date());
                smember.updateById();
            }

            //会员升级立即
            if (shengji) {
                List<CoupontplMember> mmbquans =
                        coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>().eq("sid", sid).eq("mlevel", tolevel));

                for (CoupontplMember item : mmbquans) {
                    CouponTpl ctpl = couponTplService.selectById(item.getTplid());
                    //赠送转发者升级后新会员优惠券N张
                    for (int i = 0; i < item.getNum(); i++) {
                        //非转发非赠送券的动作，此处是转发商家会会员权益
                        //而发放的会员券是领取成为商家会员之后
                        couponService.lingQuantongji("", null, shareid, ctpl, Qgettype.huiyuan, i == 0);
                    }
                }
            }
        }

        return flag;
    }

}
